package com.zhijs.struts.action;

import static java.lang.System.out;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;

import com.h819.core.db.MyDbUtils;
import com.h819.core.web.jqgrid.JqgridListBaseAction;
import com.h819.core.web.jqgrid.JqgridUtils;

;

/**
 * @ClassName: ShowListBydepartment
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author h819
 * @date 2010-1-7 下午03:38:42
 * @version V1.0
 */

/**
 * 实现方法同 ShowUpdateAction
 */

public class ShowDifferListAction extends JqgridListBaseAction implements
		SessionAware {

	private Logger log = Logger.getLogger(ShowDifferListAction.class);

	Map session;

	private String departmentid;
	private QueryRunner runner = new QueryRunner();;
	private Connection conn = null;

	com.h819.core.web.jqgrid.Page p = this.getPage();

	int totalRecords;

	// 每页记录数
	// int pageSize = conf.getInt("pagesize");// 每页显示记录数，默认为10条;
	// 默认当前页
	int defaultPage = 1;
	// 当前页数
	int page = 0;

	public String execute() throws Exception {

		if (this.isSearch()) {
			search();

		} else {
			// 准备数据
			prepareListDate(null, null);
		}

		// 以下变量，必须赋值
		this.setCurPageNo(p.getPageNo());
		this.setTotalPages(p.getTotalPages());
		this.setTotalRecords(p.getTotalCount());
		this.setDataRows(this.getDataRows());

		// 测试结果
		log.info("当前页号：" + p.getPageNo());
		log.info("每页显示数据数量：" + p.getPageSize());
		log.info("数据总量：" + p.getTotalCount());
		log.info("排序变量：" + p.getOrderBy());
		log.info("升序/降序：" + p.getOrder());

		// 测试数据
		for (Map m : this.getDataRows()) {
			StringUtils.center("当前页面的数据 ", 80, '*');
			for (Iterator it = m.entrySet().iterator(); it.hasNext();) {
				Map.Entry entry = (Map.Entry) it.next();
				System.out.println(entry.getKey() + " = " + entry.getValue());
			}
		}

		return SUCCESS;
	}

	/**
	 * 按照部门，返回该部门所有托管标准列表
	 */
	private void prepareListDate(String st_standard_code, String oper) {

		conn = MyDbUtils.getInstance("h819.properties").getOracleConnection235();

		try {

			// 计算记录数目
			String queryCountDiffer = "select count(1)  from zhijs_standard_view zjsv where "
					+ "not exists(select 1 from st_standard stda where zjsv.st_standardcode = stda.standard_code) and "
					+ "zjsv.st_type ='1'";

			log.info("queryCountDiffer : " + queryCountDiffer);

			// 计算记录总数
			Map<String, Object> r7 = runner.query(conn, queryCountDiffer,
					new MapHandler());
			for (Iterator it = r7.entrySet().iterator(); it.hasNext();) {
				Map.Entry entry = (Map.Entry) it.next();
				totalRecords = Integer.parseInt(entry.getValue().toString());
				// out.println(entry.getKey() + " = " + entry.getValue());
			}

			// 给 page 设置必要参数
			p.setTotalCount(totalRecords);

			// 计算分页
			int begin = p.getFirst();
			int end = begin + p.getPageSize() - 1;
			if (end >= this.getTotalRecords())
				end = Long.valueOf(this.getTotalRecords()).intValue();
			// 起始位置
			String limitFrom = String.valueOf(begin);
			// 结束位置
			String limitTo = String.valueOf(end);

			log.info("in zhijs : limitFrom = " + limitFrom);
			log.info("in zhijs : limitTo = " + limitTo);

			// 按照部门查询

			String queryDifferList = "select temptable.* from( "
					+ "select zjsv.*,"
					+ "row_number() over(order by zjsv.st_type) as num "
					+ "from zhijs_standard_view zjsv where "
					+ "not exists(select 1 from st_standard b where zjsv.st_standardcode = b.standard_code) and "
					+ "zjsv.st_type ='1' )temptable where num between " + limitFrom
					+ " AND " + limitTo;

			log.info("queryDifferList = " + queryDifferList);

			List<Map<String, Object>> listDiffer;

			listDiffer = runner.query(conn, queryDifferList,
					new MapListHandler());

			this.setDataRows(listDiffer);
			//
			// // 重新构造返回值，每次都重新初始化
			// List<Map<String, Object>> newSearchData = new
			// ArrayList<Map<String, Object>>();
			//			
			// if (listDiffer != null)
			//
			// for (Map standardMap : listDiffer) {// 查询所有的标准,每次循环是一条标准题录
			//
			// // 临时变量，重新组合数据用重新构造返回值
			// Map<String, Object> tempStandardMap = new TreeMap<String,
			// Object>();
			//
			// for (Iterator it = standardMap.entrySet().iterator(); it
			// .hasNext();) { // 每条标准的具体信息
			// Map.Entry entry = (Map.Entry) it.next();
			// StringUtils.center("key = value", 80, "*");
			// log.info(entry.getKey() + " = " + entry.getValue());
			//
			//
			// if (entry.getKey().toString().equals("NUM")) {// 序号
			//
			// // 由于都转换为了 String 类型，需要判断空值
			// String value = "";
			// if (entry.getValue() != null)
			// value = entry.getValue().toString();
			//
			//
			// tempStandardMap.put(entry.getKey().toString(),
			// entry.getValue());
			//
			// } else if (entry.getKey().toString().equals(
			// "ST_LASTUPDATE")) { // 重新设置日期，这里可能设定格式化，以后再研究
			// tempStandardMap.put(entry.getKey().toString(),
			// StringUtils
			// .substringBefore(entry.getValue()
			// .toString(), "T00:00:00"));
			// } else {
			// // 其他字段不做处理
			// tempStandardMap.put(entry.getKey().toString(),
			// entry.getValue());
			// // tempMap.put("ACTION", "更新");
			// }
			//
			// }// 查询单条托管标准详细信息完成
			// newSearchData.add(tempStandardMap);
			//
			// }// 逐条查询托管标准完成
			//
			// this.setDataRows(newSearchData);

		} catch (SQLException e) {
			DbUtils.printStackTrace(e);
		} finally {
			DbUtils.closeQuietly(conn);
		}
	}

	/**
	 * search 操作，仅提供 标准号搜索
	 */
	private void search() {

		log.info("in search action:");
		log.info("search filed:" + this.getSearchField());
		log.info("search string:" + this.getSearchString());
		log.info("search oper:"
				+ JqgridUtils.getOperSqlName(this.getSearchOper()));

		this.prepareListDate(this.getSearchString().trim(), JqgridUtils
				.getOperSqlName(this.getSearchOper()));

	}

	/*
	 * 以下getter方法必须实现，struts2-json插件会将这些getter方法序列化，以便输出json对象。
	 * 这些getter方法只需返回相应的属性即可。如getCurPage应该返回curPage （curPage在JsonBaseAction中有定义）
	 */
	@Override
	public int getCurPageNo() {
		return this.curPageNo;
	}

	@Override
	public List<Map<String, Object>> getDataRows() {
		return this.dataRows;
	}

	@Override
	public long getTotalPages() {
		return this.totalPages;
	}

	@Override
	public long getTotalRecords() {
		return this.totalRecords;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public String getDepartmentid() {
		return departmentid;
	}

	public void setDepartmentid(String departmentid) {
		this.departmentid = departmentid;
	}

}
